package com.nova.edc.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import com.nova.edc.model.system.CustomerInfo;
import com.nova.edc.service.system.CustomerInfoService;
import com.nova.frame.utils.JdbcUtils;
import com.seio.edc.util.IntegerUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.nova.edc.dao.system.LoginDao;
import com.nova.edc.dao.system.RoleDao;
import com.nova.edc.model.system.Login;
import com.nova.edc.model.system.Role;
import com.nova.edc.service.system.LoginService;
import com.nova.edc.service.system.RoleService;
import com.nova.frame.dao.buzz.query.Order;
import com.nova.frame.dao.buzz.query.Query;
import com.nova.frame.dao.criterion.Restrictions;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.frame.utils.StringUtils;
import com.nova.module.filter.query.Filter;

public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginDao novaLoginDao;

    @Autowired
    private RoleDao novaRoleDao;

    @Autowired
    private RoleService novaRoleService;

    @Autowired
    private CustomerInfoService novaCustomerInfoService;

    @Override
    public int getExtCount() {
        return novaLoginDao.getExtCount();
    }

    @Override
    public PageList<Login> findLoginPageList(Login login, Page page,
                                             String sidx, String sord, Login sessionLogin) {
        Query<Login> query = novaLoginDao.query();
        List<Role> roleList = novaRoleService.findByRoleParent(sessionLogin
                .getRoleid());
        List<Integer> roleIdList = novaRoleService.findRoleId(roleList);
        query.add(Restrictions.in("t_login.Roleid", roleIdList))
                .add(Restrictions.eq("t_login.ParentId", sessionLogin.getId()))
                .add(Restrictions.eq("t_login.Scrapped", 0))
                .addOrder(Order.custom(sord, sidx));
        int code = 0;
        if (StringUtils.isNotNullOrEmpty(login.getCompanycode()) || com.nova.module.util.StringUtils.isNotNullOrEmpty(login.getCustomername())) {
            if (StringUtils.isNotNullOrEmpty(login.getCompanycode())) {
                code = Integer.parseInt(login.getCompanycode());
            }
            List<CustomerInfo> infos = novaCustomerInfoService.findByCodeName(code, login.getCustomername());
            List<Integer> customerinfoId = novaCustomerInfoService.getCustomerinfoId(infos);
            if (customerinfoId != null && customerinfoId.size() > 0) {
                query.add(Restrictions.in("t_login.CustomerInfoId", customerinfoId));
            } else {
                query.add(Restrictions.in("t_login.CustomerInfoId", 0));
            }
        }
        Filter.addFilterCondition(query, login);
        return query.pageList(page);
    }

    @Override
    public PageList<Login> findAgentLoginPageList(int loginId, Page page,
                                                  String sidx, String sord, String username) {
        Login login = novaLoginDao.getById(String.valueOf(loginId));
        List<Login> logins = new ArrayList<Login>();
        logins.add(login);
        findChildAgent(login, logins, sidx, sord);
        Query<Login> query = novaLoginDao
                .query()
                .add(Restrictions.eq("t_login.Roleid", novaRoleDao
                        .getCommonUser().getId()))
                .add(Restrictions.in("t_login.ParentId",
                        getParentIdList(logins)))
                .add(Restrictions.eq("t_login.Scrapped", 0))
                .addOrder(Order.custom(sord, sidx));
        logins.addAll(query.list());
        List<Login> deleteLogins = new ArrayList<Login>();
        if (StringUtils.isNotNullOrEmpty(username)) {
            for (int i = 0; i < logins.size(); i++) {
                if (!logins.get(i).getUsername().equals(username)) {
                    deleteLogins.add(logins.get(i));
                }
            }
        }
        logins.removeAll(deleteLogins);
        PageList<Login> list = new PageList<Login>();
        list.setDatas(logins);
        page.make(logins.size());
        list.setPage(page);
        return list;
    }

    public void findChildAgent(Login login, List<Login> logins, String sidx,
                               String sord) {
        Role childRole = novaRoleDao.getRoleByParent(login.getRoleid());
        if (childRole != null) {
            Query<Login> query = novaLoginDao.query()
                    .add(Restrictions.eq("t_login.Roleid", childRole.getId()))
                    .add(Restrictions.eq("t_login.ParentId", login.getId()))
                    .add(Restrictions.eq("t_login.Scrapped", 0))
                    .addOrder(Order.custom(sord, sidx));
            List<Login> agentLogins = query.list();
            logins.addAll(agentLogins);
            for (int i = 0; i < agentLogins.size(); i++) {
                findChildAgent(agentLogins.get(i), logins, sidx, sord);
            }
        }
    }

    public List<Integer> getParentIdList(List<Login> list) {
        List<Integer> items = new ArrayList<Integer>();
        for (int i = 0; i < list.size(); i++) {
            items.add(list.get(i).getId());
        }
        return items;
    }

    @Override
    public Login insert(Login login) {
        return novaLoginDao.insert(login);
    }

    @Override
    public int update(Login login) {
        return novaLoginDao.updateNotNull(login);
    }

    @Override
    public Login getById(int id) {
        return novaLoginDao.getById(String.valueOf(id));
    }

    @Override
    public int deleteById(int id) {
        return novaLoginDao.deleteById(id);
    }

    @Override
    public Login getLogin(Login login) {
        return novaLoginDao.getByExample(login);
    }

    @Override
    public boolean isExistLogin(String username, Integer id) {
        Query<Login> query = novaLoginDao.query()
                .add(Restrictions.eq("t_login.UserName", username))
                .add(Restrictions.eq("t_login.Scrapped", 0));
        if (id != null && id != 0) {
            query.add(Restrictions.ne("t_login.ID", id));
        }
        int count = query.list().size();
        return count == 0;
    }

    @Override
    public Login isExistLogin(String username, String password) {
        Query<Login> query = novaLoginDao.query()
                .add(Restrictions.eq("t_login.UserName", username))
                .add(Restrictions.eq("t_login.Password", password))
                .add(Restrictions.eq("t_login.Scrapped", 0));
        return query.get();
    }

    @Override
    public void trimLogin(Login login) {
        if (StringUtils.isNotNullOrEmpty(login.getUsername())) {
            login.setUsername(login.getUsername().trim());
        }
    }

    @Override
    public void emptyCompanyByid(Integer id) {
        String sql = "UPDATE t_login SET CustomerInfoId = NULL WHERE ID = ?";
        JdbcUtils.execute(sql, id);
    }

    @Override
    public List<Login> findByRoleId(Integer id) {
        Query<Login> query = novaLoginDao.query()
                .add(Restrictions.eq("t_login.Roleid", id));
        return query.list();
    }
}
